#include "producteditor.h"
#include "ui_producteditor.h"
#include "database/databasequery.h"
#include "database/dbtabproduct.h"
#include "dataview/productmodel.h"
#include "common/floatcompara.h"
#include <QValidator>
#include <QRegExp>


ProductEditor::ProductEditor(const QModelIndex &index,QWidget *parent) :
    BaseEditor(index,parent),
    ui(new Ui::ProductEditor)
{
    ui->setupUi(this);
    setWindowFlags(Qt::FramelessWindowHint);
    connect(this,SIGNAL(accepted()),this,SLOT(onAccept()));
    this->setGeometry(WINDOW_GEOMETRY_SHIFT(0.4,0.4,0));
    if(!mIsNew)
    {
        ui->leName->setText(index.data(ProductModel::ROLE_NAME).toString());
        ui->leHI->setText(index.data(ProductModel::ROLE_HI).toString());
        ui->leOk->setText(index.data(ProductModel::ROLE_OK).toString());
        ui->leLo->setText(index.data(ProductModel::ROLE_LOW).toString());
    }
    QRegExp regexp("^[0-9]+\\.([0-9]{1,4})?$");
    QValidator *validator = new QRegExpValidator(regexp);
    ui->leHI->setValidator(validator);
    ui->leLo->setValidator(validator);
    ui->leOk->setValidator(validator);
}

ProductEditor::~ProductEditor()
{
    delete ui;
}


void ProductEditor::on_btn_cancel_clicked()
{
    this->reject();
}

void ProductEditor::on_btn_ok_clicked()
{
    QString name = ui->leName->text();
    QString hi = ui->leHI->text();float hi_f = hi.toFloat();
    QString ok = ui->leOk->text();float ok_f = ok.toFloat();
    QString lo = ui->leLo->text();float lo_f = lo.toFloat();
    if(name.isEmpty()||hi.isEmpty()||ok.isEmpty()||lo.isEmpty())
    {
        MyMessageDialog::warning(0,"错误","请输入完整的数据");
        return;
    }
    if(F_BZ(lo_f-ok_f)||F_BZ(lo_f-hi_f)||F_BZ(ok_f-hi_f))
    {
        MyMessageDialog::warning(0,"错误","数据错误");
        return;
    }
    DataBaseQuery query;
    bool accept =false;
    QMap<QString,QVariant> dataMap;
    dataMap.insert(DBTabProduct::_NAME,name);
    dataMap.insert(DBTabProduct::_HI,hi);
    dataMap.insert(DBTabProduct::_OK,ok);
    dataMap.insert(DBTabProduct::_LOW,lo);
    if(DBTabProduct::isExist(DBTabProduct::TAB_NAME,DBTabProduct::_NAME,name))
    {
        QString opt = QString(" \"%1\" = \"%2\"").arg(DBTabProduct::_NAME).arg(name);
        accept = query.updateItem(DBTabProduct::TAB_NAME,dataMap,opt);
    }
    else
    {
        accept = query.insert(DBTabProduct::TAB_NAME,dataMap);
    }
    if(accept)
        this->accept();
    else
        this->reject();

}

void ProductEditor::onAccept()
{
    emit updateData();
}
